package com.cqfae.deploycentral.app.services.impl;

import com.cqfae.deploycentral.api.utils.IdGenerator;
import com.cqfae.deploycentral.app.base.BaseConstantCode;
import com.cqfae.deploycentral.app.base.BaseConstants;
import com.cqfae.deploycentral.app.config.DeployInfo;
import com.cqfae.deploycentral.app.config.JenkinsInfo;
import com.cqfae.deploycentral.app.dao.entity.AppInfo;
import com.cqfae.deploycentral.app.dao.entity.DeployHistory;
import com.cqfae.deploycentral.app.dao.mapper.AppInfoMapper;
import com.cqfae.deploycentral.app.dao.mapper.DeployHistoryMapper;
import com.cqfae.deploycentral.app.services.RemoteService;
import com.cqfae.deploycentral.app.utils.ConvertUtil;
import com.cqfae.deploycentral.app.utils.GsonUtils;
import com.cqfae.deploycentral.app.utils.NullUtil;
import com.cqfae.deploycentral.app.web.request.PinganGwRequest;
import com.cqfae.deploycentral.app.web.response.MailResponse;
import com.cqfae.deploycentral.app.web.vo.JenkinsRemoteVo;
import com.cqfae.deploycentral.app.web.vo.WindowPlansTagVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Date;

/**
 * Created by YANGHENG940 on 2017/8/9.
 */
@Service
@Transactional
public class RemoteServiceImpl implements RemoteService {

    private static Logger logger = LoggerFactory.getLogger(RemoteServiceImpl.class);

    @Autowired
    private IdGenerator idGenerator;

    @Autowired
    private AppInfoMapper appInfoMapper;

    @Autowired
    private JenkinsInfo jenkinsInfo;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DeployHistoryMapper deployHistoryMapper;

    @Autowired
    private DeployInfo deployInfo;

    @Override
    public int invokeJenkins(WindowPlansTagVo tag, String action) {
        int count = 0;
        if (NullUtil.isNotEmpty(tag)) {
            Long hisstoryId = idGenerator.nextId();
            AppInfo appInfo = new AppInfo();
            appInfo.setAppName(tag.getAppName());
            appInfo = appInfoMapper.selectOne(appInfo);
            Assert.isTrue(NullUtil.isNotEmpty(appInfo), "未发现项目名称：" + tag.getAppName());
            JenkinsRemoteVo vo = new JenkinsRemoteVo();
            vo.setJenkinsHost(jenkinsInfo.getHost());
            vo.setJenkinsBuildUrl(appInfo.getBuildUrl());
            vo.setToken(jenkinsInfo.getToken());
            vo.setTag(tag.getTagInfo());
            vo.setCallBackHost(jenkinsInfo.getCallBackHost());
            //vo.setCallBackMethod(jenkinsInfo.getCallBackMethod());
            //vo.setEnv(jenkinsInfo.getEnv());
            vo.setCallBackId(hisstoryId.toString());
            vo.setAppCheckUrl(appInfo.getCheckUrl());
            vo.setAppPort(appInfo.getPort().toString());
            vo.setStatus("0");
            vo.setAction(action);
            String remoteUrl = ConvertUtil.createJenkinsRemoteUrl(vo);
            logger.info("===== Jenkins Remote Call ===== {}", remoteUrl);
            ResponseEntity<String> responseEntity = restTemplate.exchange(remoteUrl,
                    HttpMethod.GET, null, String.class);
            HttpStatus status = responseEntity.getStatusCode();
            //写入发布历史
            if (status.is2xxSuccessful()) {
                DeployHistory deployHistory = new DeployHistory();
                deployHistory.setId(hisstoryId);
                deployHistory.setWindowPlansTagId(tag.getId());
                deployHistory.setReportTagId(tag.getReportTagId());
                deployHistory.setAppName(appInfo.getAppName());
                deployHistory.setReportCode(tag.getReportCode());
                deployHistory.setTag(tag.getTagInfo());
                deployHistory.setEnv(System.getProperty("spring.profiles.active"));
                if (action.equals(deployInfo.getRollback())) {
                    deployHistory.setDeployStatus(BaseConstantCode.DEPLOY_ROLLBACK_ING);
                } else {
                    deployHistory.setDeployStatus(BaseConstantCode.DEPLOY_STATUS_PROCESSING);
                }
                deployHistory.setBuildId(0);
                deployHistory.setCreateBy("123");
                deployHistory.setCreateTime(new Date());
                count = deployHistoryMapper.insert(deployHistory);
            }
        }
        return count;
    }

    @Override
    public MailResponse sendMailToTester(String url, PinganGwRequest request) {
        LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add(BaseConstants.mailHeader, GsonUtils.getInstance().toJson(request));
        HttpEntity<LinkedMultiValueMap> formEntity = new HttpEntity<>(map);
        return restTemplate.postForObject(url, formEntity, MailResponse.class);
    }
}
